package lzupdater.net;

import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import lzupdater.log.Logger;
import lzupdater.log.LoggerLevel;

//LZRosterUpdater, a java client to update LZRoster
//Copyright (C) 2008 Fraskor from Krasus (e-mail: fraskor@gmail.com)
//
//This file is part of LZRosterUpdater.
//
//LZRosterUpdater is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

/**
 * 
 * @author Fraskor
 */
public class Cookies {
	private Logger logger;
	private HashMap<String, String> cookies = new HashMap<String, String>();

	public Cookies(URLConnection connection, Logger logger) {
		this.logger = logger;
		cookies.clear();
		addCookies(connection);
	}

	public Cookies(Cookies source) {
		logger = source.logger;
		cookies.clear();
		cookies.putAll(source.cookies);
	}

	private Cookies(Cookies source, String... keyToCopy) {
		logger = source.logger;
		cookies.clear();
		for (int i = 0; i < keyToCopy.length; i++) {
			String value = source.getCookie(keyToCopy[i]);
			if (value != null) {
				cookies.put(keyToCopy[i], value);
			}
		}
	}

	public Cookies extract(String... keyToCopy) {
		return new Cookies(this, keyToCopy);
	}

	public void addCookies(URLConnection connection) {
		String field = connection.getHeaderField("Set-Cookie");
		if (field != null) {
			String[] data = field.split(";");
			for (int i = 0; i < data.length; i++) {
				int idx = data[i].indexOf("=");
				cookies.put(data[i].substring(0, idx), data[i]
						.substring(idx + 1));
			}
		}
	}

	public void clear() {
		cookies.clear();
	}

	public void merge(Cookies cookiesAAjouter) {
		for (Entry<String, String> entry : cookiesAAjouter.cookies.entrySet()) {
			if (!cookies.containsKey(entry.getKey())) {
				cookies.put(entry.getKey(), entry.getValue());
			}
		}
	}

	public void sendCookies(URLConnection connection) {
		StringBuffer cookieList = new StringBuffer();

		for (Iterator<Entry<String, String>> i = cookies.entrySet().iterator(); i
				.hasNext();) {
			Entry<String, String> entry = i.next();

			cookieList.append(entry.getKey()).append('=').append(
					entry.getValue());

			if (i.hasNext()) {
				cookieList.append("; ");
			}
		}
		if (cookieList.length() > 0) {
			connection.setRequestProperty("Cookie", cookieList.toString());
		}
	}

	public String getCookie(String name) {
		return cookies == null ? null : cookies.get(name);
	}

	public void dump(Logger logger) {
		for (Entry<String, String> entry : cookies.entrySet()) {
			logger.format(LoggerLevel.DEBUG, "  Cookie[%s]='%s'", entry
					.getKey(), entry.getValue());
		}
	}

}
